﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BaseUi
{
    /// <summary>
    /// json时间转换器
    /// </summary>
    public class JsonDateTimeConverter : JsonConverter<DateTime?>
    {
        public override DateTime? ReadJson(JsonReader reader, Type objectType, DateTime? existingValue, bool hasExistingValue, JsonSerializer serializer)
        {
            var dateTimeString = reader.Value?.ToString();
            if (!string.IsNullOrEmpty(dateTimeString))
            {
                try
                {
                    return DateTime.ParseExact(dateTimeString, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
                }
                catch (FormatException)
                {
                    throw new JsonSerializationException("Invalid date time format.");
                }
            }
            return null;
        }

        public override void WriteJson(JsonWriter writer, DateTime? value, JsonSerializer serializer)
        {
            writer.WriteValue(value?.ToString("yyyy-MM-dd HH:mm:ss"));
        }
    }
}
